package com.ibeeking.found.common.db.aop;

import com.ibeeking.found.common.db.annotation.EnableMultiTenancyDB;
import com.ibeeking.found.common.db.util.DataSourceUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @ClassName DataSourceAop
 * @Description
 * @Author ibeeking
 * @Date 2020-11-05 11:32
 **/
@Aspect
@ConditionalOnMissingBean(annotation = EnableMultiTenancyDB.class)
@Component
@Order(-1)
public class DefaultDataSourceAop {

    @Pointcut("execution(* com.ibeeking..*.*Controller.*(..))")
    public void changeDSHandle() {
    }

    @Pointcut("execution(* org.jeec*.modules.jmreport.desreport.a.*.*(..))")
    public void changeJimuDSHandle() {
    }

    @Around(("changeDSHandle()"))
    public Object changeDSHandle(ProceedingJoinPoint point) throws Throwable {
        try {
            //切换数据源
            DataSourceUtils.loadReadWriteDateSource(DataSourceUtils.writeOrRead(point, (MethodSignature) point.getSignature()));
            return point.proceed();
        } finally {
            //清除数据源
            DataSourceUtils.clear();
        }
    }

    @Around(("changeJimuDSHandle()"))
    public Object changeJimuDSHandle(ProceedingJoinPoint point) throws Throwable {
        try {
            //切换数据源
            DataSourceUtils.loadReadWriteDateSource(DataSourceUtils.writeOrRead(point, (MethodSignature) point.getSignature()));
            return point.proceed();
        } finally {
            //清除数据源
            DataSourceUtils.clear();
        }
    }
}
